package com.cloudkinto.service.consumer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cloudkinto.common.RabbitQueueConstant;
import com.cloudkinto.service.consumer.vo.orderSyncRecord.PlatformOrderSyncRecordReq;
import com.cloudkinto.service.consumer.vo.rakuten.RakutenOrderUpdateConReq;
import com.cloudkinto.service.consumer.vo.shopify.ShopifyConsumerReq;
import com.cloudkinto.service.platform.PlatformOrderShopifySyncService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

@Slf4j
@Component
@RequiredArgsConstructor
public class PlatformOrderShopifyConsumer {
    private final PlatformOrderShopifySyncService platformOrderShopifySyncOrderService;
    private final RabbitTemplate rabbitTemplate;
    /**
     * 同步订单表
     * @param msg
     */
    @RabbitListener(queuesToDeclare = @Queue(RabbitQueueConstant.PlatformStore_Shopify_Sync))
    public void syncOrderRakuten(String msg) {
        ShopifyConsumerReq req = JSONObject.parseObject(msg, ShopifyConsumerReq.class);
        String s = null;
        try {
             s = platformOrderShopifySyncOrderService.updateShopifyOrders(req);
        } catch (Exception e) {
            s = e.getMessage();
        }
        if (StringUtils.isNotBlank(s)) {
            rabbitTemplate.convertAndSend(RabbitQueueConstant.PlatformOrder_SyncRecord_Update, JSON.toJSONString(new PlatformOrderSyncRecordReq(req.getSyncId(), 3, new Date(), null, s, null)));
        }
    }


    @RabbitListener(queuesToDeclare = @Queue(RabbitQueueConstant.PlatformStore_Shopify_Update))
    public void syncOrderRakutenUpdate(String msg) {
        RakutenOrderUpdateConReq req = JSONObject.parseObject(msg, RakutenOrderUpdateConReq.class);
        try {
            platformOrderShopifySyncOrderService.consumerUpdate(req);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    /**
     * 标发
     * @param msg
     */
    @RabbitListener(queuesToDeclare = @Queue(RabbitQueueConstant.PlatformStore_Shopify_MarkShip))
    public void markShip(String msg) {
        if (StringUtils.isBlank(msg)) {
            return;
        }
        try {
            platformOrderShopifySyncOrderService.markShip(Long.parseLong(msg));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }




}
